package com.yhy.server.service;


import com.yhy.autoconfig.templates.OssTemplate;
import com.yhy.domain.UserInfo;
import com.yhy.domain.mongo.Publish;
import com.yhy.domain.mongo.RecommendUser;
import com.yhy.domain.mongo.Visitors;
import com.yhy.domain.vo.Movements;
import com.yhy.domain.vo.PageResult;
import com.yhy.domain.vo.TodayBest;
import com.yhy.dubbo.api.UserInfoApi;
import com.yhy.dubbo.api.mongo.PublishApi;
import com.yhy.dubbo.api.mongo.RecommendUserApi;
import com.yhy.dubbo.api.mongo.VisitorsApi;
import com.yhy.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {

    @Reference
    private PublishApi publishApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Reference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发布动态
     * @param publish
     * @param imageContent
     * @return
     * @throws IOException
     */
    public ResponseEntity saveMovements(Publish publish, MultipartFile[] imageContent) throws IOException {
        Long userId = UserHolder.getUserId();

        publish.setUserId(userId);

        List<String> images = new ArrayList<>();
        if(imageContent != null){
            for (MultipartFile multipartFile : imageContent) {
                String imgUrl = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                images.add(imgUrl);
            }
        }
        publish.setMedias(images);
        String publishId = publishApi.save(publish);

        //添加内容审核
        try{
            rocketMQTemplate.convertAndSend("tanhua-publishes",publishId);
        }catch (Exception e){

        }
        return ResponseEntity.ok(null);
    }


    /**
     * 查看好用动态
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity findMovements(Integer page, Integer pagesize) {

        Long userId = UserHolder.getUserId();

        PageResult pageResult = publishApi.findMovementsByUid(page,pagesize,userId);

        initPageResult(pageResult);

        return ResponseEntity.ok(pageResult);
    }

    /**
     * 重置pageResult的方法 将pageResult里的List<Publish>重新封装为LIst<Movements>
     *     其中调用了userInfoApi的findById方法
     * @param pageResult
     */
    private void initPageResult(PageResult pageResult){

        List<Publish> items = (List<Publish>) pageResult.getItems();

        List<Movements> list = new ArrayList<>();

        for (Publish item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            Movements movements = Movements.init(userInfo, item);
            if(redisTemplate.hasKey("publish_comment_like_"+UserHolder.getUserId()+"_"+item.getId().toHexString())){
                movements.setHasLiked(1);
            }
            if(redisTemplate.hasKey("publish_comment_love_"+UserHolder.getUserId()+"_"+item.getId().toHexString())){
                movements.setHasLoved(1);
            }
            list.add(movements);
        }
        pageResult.setItems(list);
    }

    public ResponseEntity recommendMovements(Integer page, Integer pagesize) {

        Long userId = UserHolder.getUserId();

        PageResult pageResult = queryRecommend(page,pagesize);
        if(pageResult == null){
            pageResult = publishApi.findMovementsByRecommend(page,pagesize,userId);
        }
        initPageResult(pageResult);

        return ResponseEntity.ok(pageResult);
    }

    private PageResult queryRecommend(Integer page, Integer pagesize) {
        //1.拼接redis的key
        String key = "QUANZI_PUBLISH_RECOMMEND_"+UserHolder.getUserId();
        //2.取出所有数据
        String value = redisTemplate.opsForValue().get(key);
        //3.如果没有数据 返回null
        if(value == null){
            return null;
        }
        //4.分页数据边界配置
        String pidStr[] = value.split(",");
        int counts = pidStr.length;
        int start = (page-1)*pagesize;
        List<Publish> list = new ArrayList<>();
        if(start<counts){
            //尾部索引确定
            int end = start + pagesize -1;
            if(end>counts){
                end=counts;
            }
            for (int i=start;i<end;i++){
                Long pid = Long.valueOf(pidStr[i]);
                Publish publish = publishApi.findByPid(pid);
                list.add(publish);
            }
        }
        //5.返回
        return new PageResult(page,pagesize,counts,list);
    }

    public ResponseEntity findOwnMovements(Integer page, Integer pagesize, Long userId) {

        PageResult pageResult = publishApi.findOwnMovements(page,pagesize,userId);
        initPageResult(pageResult);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity findMovementDetailById(String publishId) {
        Publish publish = publishApi.findMovementDetailById(publishId);

        UserInfo userInfo = userInfoApi.findById(publish.getUserId());

        Movements movements = Movements.init(userInfo, publish);

        return ResponseEntity.ok(movements);
    }

    /**
     * 谁看过我
     *
     * 需求:
     *      1.展示出最新的四条记录
     *      2.当在首页进入访客记录时,标识已经看过最新访客记录,返回首页时,清空刚才的查询
     *      为了查看最新的访客记录,需要记录查看访客记录的时间,当查看访客记录时,将查看访客记录的时间存入redis
     * @return
     */
    public ResponseEntity visitors() {
//        1.获取最新查看访客记录的时间
        String key = "visitors_time_"+UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        Long created = 0L;
        //如果取到了时间 则将查看时间放入created
        if(!StringUtils.isEmpty(value)){
            created = Long.valueOf(value);
        }
//        2.调用api查询出List<Visitors>
        List<Visitors> visitors = visitorsApi.topVisitors(UserHolder.getUserId(),created,4);
        System.out.println(visitors);

//        3.封装List<TodayBest>
        List<TodayBest> list = new ArrayList<>();
        for (Visitors visitor : visitors) {
            //查询用户信息
            UserInfo userInfo = userInfoApi.findById(visitor.getVisitorUserId());
            //查询缘分信息
            RecommendUser user = recommendUserApi.findRecommendUser(visitor.getVisitorUserId(), UserHolder.getUserId());
            TodayBest todayBest = TodayBest.init(userInfo,user);
            list.add(todayBest);
        }
        return ResponseEntity.ok(list);
    }
}